<?php

// +----------------------------------------------------------------------
// | 分销管家
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

namespace Manage\Controller;

use Think\Log;

/**
 * 微信控制器
 * @author xzake
 */
class CustomMenuController extends AdminController {

    /**
     * 菜单列表
     * @author xzake
     */
    public function index() {
        //搜索
        $keyword = (string) I('keyword');
        $condition = array('like', '%' . $keyword . '%');
        $map['id|title'] = array($condition, $condition, '_multi' => true); //搜索条件
        //获取所有菜单
        $map['status'] = array('egt', '0'); //禁用和正常状态
        $data_list = D('CustomMenu')->where($map)->order('sort desc, id desc')->select();

        //转换成树状列表
        $tree = new \Common\Util\Tree();
        $tree_list = $tree->toFormatTree($data_list);

        //使用Builder快速建立列表页面。
        $builder = new \Common\Builder\ListBuilder();
        $builder->title('菜单列表')  //设置页面标题
                ->AddNewButton()    //添加新增按钮
                ->addResumeButton() //添加启用按钮
                ->addForbidButton() //添加禁用按钮
                ->addDeleteButton() //添加删除按钮
                ->addCustomButtonAjax("重新生成菜单", U("createMenu"))
                ->setSearch('请输入ID/菜单名称', U('index'))
                ->addField('id', 'ID', 'text')
                ->addField('title_show', '标题', 'text')
                ->addField('keyword', '关键字', 'text')
                ->addField('sort', '排序', 'text')
                ->addField('status', '状态', 'status')
                ->addField('right_button', '操作', 'btn')
                ->dataList($tree_list)    //数据列表
                ->addRightButton('edit')   //添加编辑按钮
                ->addRightButton('forbid') //添加禁用/启用按钮
                ->addRightButton('delete') //添加删除按钮
                ->display();
    }

    /**
     * 新增菜单
     * @author xzake
     */
    public function add() {
        if (IS_POST) {
            $custor_menu_model = D('CustomMenu');
            $data = $custor_menu_model->create();
            if ($data) {
                $id = $custor_menu_model->add();
                if ($id) {
                    $this->success('新增成功', U('index'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($custor_menu_model->getError());
            }
        } else {
            $map['status'] = array('egt', 0);
            $map['pid'] = array('eq', 0);
            $all_group = D('CustomMenu')->where($map)->order('sort desc,id asc')->select();
            $all_group = array_merge(array(0 => array('id' => 0, 'title' => '顶级菜单')), $all_group);
            $this->assign('all_group', $all_group);
            $this->assign('event_type', C('WECHAT_MENU_EVENT_LIST'));
            $this->assign('event_type_title', C('WECHAT_MENU_EVENT_LIST_TITLE'));
            $this->meta_title = '新增菜单';
            $this->display('Public/custom_menu');
        }
    }

    /**
     * 编辑菜单
     * @author xzake
     */
    public function edit($id) {
        if (IS_POST) {
            $custor_menu_model = D('CustomMenu');

            $data = $custor_menu_model->create();
            if ($data) {
                if ($custor_menu_model->save() !== false) {
                    $this->success('更新成功', U('index'));
                } else {
                    $this->error('更新失败');
                }
            } else {
                $this->error($custor_menu_model->getError());
            }
        } else {
            $info = D('CustomMenu')->find($id);

            $map['status'] = array('egt', 0);
            $map['pid'] = array('eq', 0);
            $all_group = D('CustomMenu')->where($map)->order('sort asc,id asc')->select();
            $all_group = array_merge(array(0 => array('id' => 0, 'title' => '顶级菜单')), $all_group);
            $this->assign('all_group', $all_group);
            $this->assign('event_type', C('WECHAT_MENU_EVENT_LIST'));
            $this->assign('event_type_title', C('WECHAT_MENU_EVENT_LIST_TITLE'));
            $this->assign('info', $info);
            $this->meta_title = '编辑菜单';
            $this->display('Public/custom_menu');
        }
    }

    public function createMenu() {
        $map['status'] = array('egt', 0);
        $tree = new \Common\Util\Tree();
        $data_list = D('CustomMenu')->where($map)->order('sort desc,id desc')->select();
        $menuList = array();
        foreach ($data_list as $value) {
            $menuList[] = array(
                'id' => $value['id'],
                'pid' => $value['pid'],
                'name' => $value['title'],
                'type' => $value['type'],
                'code' => empty($value['keyword']) ? "" : $value['keyword'],
            );
        }

        //树形排布
        $menuList2 = $menuList;
        foreach ($menuList as $key => $menu) {
            foreach ($menuList2 as $k => $menu2) {
                if ($menu['id'] == $menu2['pid']) {
                    $menuList[$key]['sub_button'][] = $menu2;
                    unset($menuList[$k]);
                }
            }
        }
        //处理数据
        foreach ($menuList as $key => $menu) {
            //处理type和code
            if (@$menu['type'] == 'view') {
                $menuList[$key]['url'] = $menu['code'];
            } else if (@$menu['type'] == 'click') {
                $menuList[$key]['key'] = $menu['code'];
            } else if (@!empty($menu['type'])) {
                $menuList[$key]['key'] = $menu['code'];
                if (!isset($menu['sub_button']))
                    $menuList[$key]['sub_button'] = array();
            }
            unset($menuList[$key]['code']);
            //处理PID和ID
            unset($menuList[$key]['id']);
            unset($menuList[$key]['pid']);
            //处理子类菜单
            if (isset($menu['sub_button'])) {
                unset($menuList[$key]['type']);
                foreach ($menu['sub_button'] as $k => $son) {
                    //处理type和code
                    if ($son['type'] == 'view') {
                        $menuList[$key]['sub_button'][$k]['url'] = $son['code'];
                    } else if ($son['type'] == 'click') {
                        $menuList[$key]['sub_button'][$k]['key'] = $son['code'];
                    } else {
                        $menuList[$key]['sub_button'][$k]['key'] = $son['code'];
                        $menuList[$key]['sub_button'][$k]['sub_button'] = array();
                    }
                    unset($menuList[$key]['sub_button'][$k]['code']);
                    //处理PID和ID
                    unset($menuList[$key]['sub_button'][$k]['id']);
                    unset($menuList[$key]['sub_button'][$k]['pid']);
                }
            }
        }
        //整理格式
        $data = array();
        $data['button'] = array_values($menuList);

        $w = D('Wechat')->find(1);
        $option['token'] = $w['token'];
        $option['appid'] = $w['appid'];
        $option['secret'] = $w['secret'];
        $option['aeskey'] = $w['encodingaeskey'];
        Log::write("Wechat Init Option:" . json_encode($option));
//        dump($option);exit;

        $wechat = new \Common\WeChat\Wechat($option);
        $wechat->getToken();
        if ($wechat->menu_create($data)) {
            $this->success('菜单生成成功', '', IS_AJAX);
        } else {
            $this->error($wechat->getError(), '', IS_AJAX);
        }
    }

    public function delCallback($model, $map) {
        
    }

    /**
     * 创建菜单
     * @param array $data 菜单数组数据
     * example:
     * 	array (
     * 	    'button' => array (
     * 	      0 => array (
     * 	        'name' => '扫码',
     * 	        'sub_button' => array (
     * 	            0 => array (
     * 	              'type' => 'scancode_waitmsg',
     * 	              'name' => '扫码带提示',
     * 	              'key' => 'rselfmenu_0_0',
     * 	            ),
     * 	            1 => array (
     * 	              'type' => 'scancode_push',
     * 	              'name' => '扫码推事件',
     * 	              'key' => 'rselfmenu_0_1',
     * 	            ),
     * 	        ),
     * 	      ),
     * 	      1 => array (
     * 	        'name' => '发图',
     * 	        'sub_button' => array (
     * 	            0 => array (
     * 	              'type' => 'pic_sysphoto',
     * 	              'name' => '系统拍照发图',
     * 	              'key' => 'rselfmenu_1_0',
     * 	            ),
     * 	            1 => array (
     * 	              'type' => 'pic_photo_or_album',
     * 	              'name' => '拍照或者相册发图',
     * 	              'key' => 'rselfmenu_1_1',
     * 	            )
     * 	        ),
     * 	      ),
     * 	      2 => array (
     * 	        'type' => 'location_select',
     * 	        'name' => '发送位置',
     * 	        'key' => 'rselfmenu_2_0'
     * 	      ),
     * 	    ),
     * 	)
     * 
     * array(1) {
      ["button"] => array(3) {
      [0] => array(3) {
      ["name"] => string(36) "%E5%95%86%E5%9F%8E%E9%A6%96%E9%A1%B5"
      ["type"] => string(4) "view"
      ["url"] => string(26) "http%3A%2F%2Fwww.baidu.com"
      }
      [1] => array(3) {
      ["name"] => string(36) "%E9%80%80%E8%B4%A7%E6%9D%A1%E4%BE%8B"
      ["type"] => string(5) "click"
      ["key"] => string(12) "退货条例"
      }
      [2] => array(3) {
      ["name"] => string(36) "%E6%88%91%E7%9A%84%E6%9C%8D%E5%8A%A1"
      ["sub_button"] => array(2) {
      [0] => array(3) {
      ["name"] => string(36) "%E6%88%91%E7%9A%84%E8%AE%A2%E5%8D%95"
      ["type"] => string(5) "click"
      ["key"] => string(12) "我的订单"
      }
      [1] => array(3) {
      ["name"] => string(36) "%E4%BC%9A%E5%91%98%E4%B8%AD%E5%BF%83"
      ["type"] => string(5) "click"
      ["key"] => string(12) "会员中心"
      }
      }
      ["key"] => string(0) ""
      }
      }
      }

     * type可以选择为以下几种，其中5-8除了收到菜单事件以外，还会单独收到对应类型的信息。
     * 1、click：点击推事件
     * 2、view：跳转URL
     * 3、scancode_push：扫码推事件
     * 4、scancode_waitmsg：扫码推事件且弹出“消息接收中”提示框
     * 5、pic_sysphoto：弹出系统拍照发图
     * 6、pic_photo_or_album：弹出拍照或者相册发图
     * 7、pic_weixin：弹出微信相册发图器
     * 8、location_select：弹出地理位置选择器
     * 
     */
}
